const mysql = require("mysql");
require('dotenv').config();

const db = mysql.createPool({
  host: process.env.MYSQL_HOST,
  user: process.env.MYSQL_USER,
  password: process.env.MYSQL_PASSWORD,
  database: process.env.MYSQL_DATABASE,
});

const query = function (sql, values) {
  // 返回一个 Promise
  return new Promise((resolve, reject) => {
    db.getConnection(function (err, connection) {
      if (err) {
        reject(err)
      } else {
        connection.query(sql, values, (err, rows) => {

          if (err) {
            reject(err)
          } else {
            resolve(rows)
          }
          // 结束会话
          connection.release()
        })
      }
    })
  })
};

const getSessionUser = async function (sessionId) {
  const result = await query("SELECT * FROM session_user WHERE ?", { session_id: sessionId })
  
  if (!result || result.length == 0) {
    return null
  }
  const obj = JSON.parse(JSON.stringify(result));
  return obj[0]
}

const getOrder = async function (orderId) {
  const result = await query("SELECT * FROM transfer_submit WHERE ?", { order_id: orderId })
  
  if (!result || result.length == 0) {
    return null
  }
  const obj = JSON.parse(JSON.stringify(result));
  return obj[0]
}

const createOrder = async function (orderId) {
  let insertRes = await query("INSERT INTO transfer_submit SET ?", { order_id: orderId });
  return insertRes
}

exports.db = db
exports.query = query
exports.getSessionUser = getSessionUser
exports.getOrder = getOrder
exports.createOrder = createOrder
